import axios from 'axios'
import { useCookie } from '@/stores/cookie'
import router from '@/router'
import { ElMessage } from 'element-plus'
import { useUser } from '@/stores/user'
const baseURL = import.meta.env.VITE_APP_BASEAPI
const service = axios.create({ baseURL })
const user = useUser()
service.interceptors.request.use(config => {
  const { cookie } = useCookie()
  // 如果params里面有cookie，就不用再加了
  if (config.params && config.params.cookie) {
    return config
  }
  if (cookie) {
    // config.headers.Cookie = cookie
    //每个请求都带上cookie，写在url后面
    config.url += config.url.includes('?') ? '&cookie=' : '?cookie='
    config.url += cookie
  }
  return config
})

service.interceptors.response.use(
  response => {
    if (response.data.code == 301) {
      ElMessage.error('请先登录')
      user.loginfrom = true
      const { removeToken } = useToken()
      const { removeUser } = useUser()
      removeToken()
      removeUser()
      router.push('/login')
    }
    if (response.data.code == 502 || response.data.code == 501) {
      ElMessage.error('遇到未知错误，请稍后再试：' + response.data.msg)
    }
    return response.data
  },
  error => {
    if (error.response.data.code == 301) {
      ElMessage.error('请先登录')
      user.loginfrom = true
      const { removeToken } = useToken()
      const { removeUser } = useUser()
      removeToken()
      removeUser()
      router.push('/login')
    } else {
      ElMessage.error('遇到未知错误，请稍后再试：' + error)
    }
    // ElMessage.error(error)
  }
)

export default service
